<template>
  <el-dialog
    class="dia-style"
    :title="title"
    :visible.sync="open"
    width="1000px"
    destroy-on-close
    :close-on-click-modal="false"
    append-to-body
  >
    <el-form ref="elForm" :model="formData" label-position="left" size="small" @submit.native.prevent>
      <el-form-item label="条件" prop="setCondition">
        <el-select v-model="formData.setCondition" placeholder="请选择">
          <el-option label="满足任一条件" value="every" />
          <el-option label="满足全部条件" value="all" />
        </el-select>
      </el-form-item>

      <div class="inline">
        <div class="table-box">
          <hk-table
            :table-data="formData.conditions"
            :table-columns="tableLabelLists"
            :show-tooltip="false"
            :show-pag="false"
            :show-index="true"
            @singleElection="singleElection"
          />
          <div style="text-align: right">
            <el-button-group style="margin-right: 10px">
              <el-button
                type="primary"
                icon="el-icon-top"
                :disabled="selIndex == 0"
                @click="upCol"
              />
              <el-button
                type="primary"
                icon="el-icon-bottom"
                :disabled="selIndex + 1 == formData.conditions.length"
                @click="downCol"
              />
            </el-button-group>
            <el-button-group>
              <el-button
                type="primary"
                icon="el-icon-minus"
                @click="reduceCol"
              />
              <el-button type="primary" icon="el-icon-plus" @click="addCol" />
            </el-button-group>
          </div>
        </div>
        <div class="right-box">
          <p v-if="!showItem">未选择条件</p>
          <div v-else>
            <el-form-item label="变量">
              <el-cascader
                v-model="selectedRow.variable"
                :options="flowForm"
                @change="handleVariableChange"
              />
            </el-form-item>
            <el-form-item label="判断条件">
              <el-select
                v-model="selectedRow.conditionalOpt"
                clearable
                placeholder="请选择"
                @change="handleOptChange"
              >
                <el-option
                  v-for="item in conditionDict"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="值">
              <!-- <el-input v-model="selectedRow.conditionalVal" @input="handleInput" /> -->
              <el-input v-if="componentsType == 'input' || componentsType == 'textarea' " v-model="selectedRow.conditionalVal" @input="handleInput" />
              <el-radio-group v-if="componentsType == 'radio'" v-model="selectedRow.conditionalVal" @input="handleInput">
                <el-radio v-for="opts in componentsOpts" :key="opts.value" :label="opts.value">{{ opts.label }}</el-radio>
              </el-radio-group>
              <el-input-number v-if="componentsType == 'number'" v-model="selectedRow.conditionalVal" @change="handleInput" />
              <el-checkbox-group v-if="componentsType == 'checkbox'" v-model="selectedRow.conditionalVal" @change="handleInput">
                <el-checkbox v-for="opts in componentsOpts" :key="opts.value" :label="opts.value">{{ opts.label }}</el-checkbox>
              </el-checkbox-group>
              <el-select v-if="componentsType == 'select'" v-model="selectedRow.conditionsValue" placeholder="请选择" @change="handleInput">
                <el-option
                  v-for="dict in componentsOpts"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
              <el-time-picker
                v-if="componentsType == 'time'"
                v-model="selectedRow.conditionalVal"
                :picker-options="{
                  selectableRange: '00:00:00 - 23:59:59'
                }"
                placeholder="选择时间"
                :value-format="componentsOpts? componentsOpts.format : 'timestamp'"
                @change="handleInput"
              />
              <el-date-picker
                v-if="componentsType == 'date'"
                v-model="selectedRow.conditionalVal"
                type="date"
                placeholder="选择日期"
                :value-format="componentsOpts? componentsOpts.format : 'timestamp'"
                @change="handleInput"
              />
            </el-form-item>
          </div>
        </div>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">保 存</el-button>
      <el-button @click="closeDia">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import HkTable from '@/components/HkTable'
import { flatten } from '../utils/fx'

import { get } from '@/utils/request'
const BASE_URL = window.baseUrl.ticket

export default {
  components: { HkTable },
  props: {
    title: {
      type: String,
      default() {
        return '跳转条件配置'
      }
    },
    flowForm: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      open: false,
      formData: {
        setCondition: 'all',
        conditions: [],
        selectedRow: {
          variable: '',
          variableLabel: '',
          conditionalOpt: '',
          conditionalOptLabel: '',
          conditionalVal: '',
          conditionalValLabel: ''
        }
      },
      tableLabelLists: [
        { label: '变量', param: 'variableLabel' },
        { label: '判断条件', param: 'conditionalOptLabel' },
        { label: '值', param: 'conditionalValLabel' }
      ],
      //   选中的行列号
      selIndex: 0,
      showItem: false,
      reverseObj: {},
      // 条件等式
      conditionDict: [{
        'label': '等于',
        'value': '=='
      }, {
        'label': '不等于',
        'value': '!='
      }, {
        'label': '小于',
        'value': '<'
      }, {
        'label': '大于',
        'value': '>'
      }, {
        'label': '小于等于',
        'value': '<='
      }, {
        'label': '大于等于',
        'value': '>='
      }],
      //  组件类型
      componentsType: 'input',
      //  组件options
      componentsOpts: []
    }
  },
  computed: {
    selectedRow() {
      return this.formData.conditions[this.selIndex]
    }
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    show() {
      this.reverseObj = flatten(this.flowForm, 'y')
      this.open = true
    },
    // 生成ID
    generateId() {
      const s = []
      const hexDigits = '0123456789abcdef'
      for (let i = 0; i < 23; i++) {
        s[i] = hexDigits.substring(Math.floor(Math.random() * 0x10), 1)
      }

      s[14] = '4'
      s[19] = hexDigits.substring((s[19] & 0x3) | 0x8, 1)
      s[8] = s[13] = s[18] = s[23] = '-'
      const uuid = s.join('') + new Date().getTime()
      return uuid
    },
    // 单行被选中
    singleElection(data) {
      this.showItem = true
      this.formData.conditions.forEach((item, index) => {
        if (item.id === data[0].id) {
          this.selIndex = index
        }
      })
    },
    upCol() {
      const lose = this.formData.conditions.splice(this.selIndex - 1, 1)
      this.formData.conditions.splice(this.selIndex, 0, lose[0])
    },
    downCol() {
      const lose = this.formData.conditions.splice(this.selIndex + 1, 1)

      this.formData.conditions.splice(this.selIndex, 0, lose[0])
    },
    // 增加行
    addCol() {
      this.formData.conditions.push({
        id: this.generateId(),
        variable: '',
        variableLabel: '',
        conditionalOpt: '',
        conditionalOptLabel: '',
        conditionalVal: '',
        conditionalValLabel: ''
      })
    },
    // 减少
    reduceCol() {
      this.formData.conditions.splice(this.selIndex, 1)
      if (this.formData.conditions.length == 0) {
        this.showItem = false
      }
    },
    // 级联选择器
    handleVariableChange(data) {
      const mixStr = data
        .reduce((arr, item) => {
          return arr.concat(this.reverseObj[item])
        }, [])
        .join('/')
      this.formData.conditions[this.selIndex].variable = data
      this.formData.conditions[this.selIndex].variableLabel = mixStr

      this.flowForm.forEach(i => {
        if (i.value === data[0]) {
          i.children.forEach(j => {
            if (j.value === data[1]) {
              this.componentsType = j.type
              this.componentsOpts = j.options
              if (j.options.remote) {
                const reg = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/g
                const reg2 = /^\//g
                if (reg.test(j.options.remoteFunc)) {
                  get(j.options.remoteFunc).then(res => {
                    this.componentsOpts = res.map(item => {
                      return {
                        value: item[j.options.props.value],
                        label: item[j.options.props.label]
                      }
                    })
                  })
                } else if (reg2.test(j.options.remoteFunc)) {
                  get(BASE_URL + j.options.remoteFunc).then(res => {
                    this.componentsOpts = res.map(item => {
                      return {
                        value: item[j.options.props.value],
                        label: item[j.options.props.label]
                      }
                    })
                  })
                }
              } else {
                this.componentsOpts = j.options.options
              }
            }
          })
        }
      })

      const _list4 = [{
        'label': '等于',
        'value': '=='
      }, {
        'label': '不等于',
        'value': '!='
      }, {
        'label': '包含',
        'value': 'contain'
      }, {
        'label': '不包含',
        'value': 'exclusive'
      }]
      const _list6 = [{
        'label': '等于',
        'value': '=='
      }, {
        'label': '不等于',
        'value': '!='
      }, {
        'label': '小于',
        'value': '<'
      }, {
        'label': '大于',
        'value': '>'
      }, {
        'label': '小于等于',
        'value': '<='
      }, {
        'label': '大于等于',
        'value': '>='
      }]
      const _type4 = ['input', 'textarea', 'radio', 'checkbox', 'select']
      if (_type4.includes(this.componentsType)) {
        this.conditionDict = _list4
      } else {
        this.conditionDict = _list6
      }
    },
    // 选择器
    handleOptChange(data) {
      const str = this.conditionDict.filter((item) => {
        return item.value === data
      })[0].label
      this.formData.conditions[this.selIndex].conditionalOpt = data
      this.formData.conditions[this.selIndex].conditionalOptLabel = str
    },
    // 输入框
    handleInput(data) {
      this.formData.conditions[this.selIndex].conditionalVal = data
      this.formData.conditions[this.selIndex].conditionalValLabel = data
    },
    // 提交
    submitForm() {
      this.$refs['elForm'].validate((valid) => {
        if (this.formData.conditions.length > 0) {
          if (this.formData.conditions.every(i => {
            return i.conditionalOpt && i.conditionalVal && i.variable
          })) {
            this.$emit('saveDia', this.formData)
          } else {
            this.$message.error('条件配置"变量、判断条件、值"不能为空')
            return
          }
        }
        this.closeDia()
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    },
    closeDia() {
      this.open = false
      this.$refs['elForm'].resetFields()
      this.showItem = false
    }
  }
}
</script>
<style lang="scss" scoped>
.el-form {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.inline {
  flex: 1;
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  .table-box {
    display: flex;
    flex-direction: column;
    width: 49%;
    height: 100%;
    .targetTable {
      flex: 1;
    }
  }
  .right-box {
    width: 49%;
    &::v-deep {
      .el-form-item__label {
        display: block !important;
        width: 100%;
      }
      .el-select,
      .el-input,
      .el-cascader {
        width: 400px !important;
      }
    }
  }
}
::v-deep {
  .el-form-item .el-form-item__label {
    display: block !important;
  }
  .el-dialog:not(.is-fullscreen) {
    height: auto !important;
  }
  .el-dialog__body {
    height: 400px !important;
    overflow: auto;
    display: flex;
    flex-direction: column;
  }
  .el-table {
    margin-top: 0;
  }
  .el-button-group > .el-button:not(:last-child) {
    margin-right: 1px;
  }
}
</style>
